package com.keshi.openplatform.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.keshi.openplatform.gateway.bean.LoggerBean;
import com.keshi.openplatform.gateway.mq.SendLogStrean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;


@Component
public class LoggerFilter extends ZuulFilter {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SendLogStrean sendLogStrean;


    /**
     * 我们应该在给用户返回数据的时候计算响应时间,所以这个filter应该是post类型
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 50;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //把我们要的数据找到,然后通过日志发送出去
        LoggerBean loggerBean = new LoggerBean();

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Date responeDate = new Date();
        loggerBean.setResponseTime(responeDate);//设置响应时间
        loggerBean.setApp_key(request.getParameter("app_key"));
        loggerBean.setApiName(request.getParameter("method"));
        loggerBean.setRemoteIp(request.getRemoteAddr());
        Date startTine = (Date) context.get("startTime");
        loggerBean.setReveivceTime(startTine);
        loggerBean.setTotalTime(responeDate.getTime() - startTine.getTime());//设置总时间
        try {
            loggerBean.setServerIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        loggerBean.setContent(request.getQueryString());

        MessageChannel messageChannel = sendLogStrean.message_channel();
        try {
            messageChannel.send(new GenericMessage<String>(objectMapper.writeValueAsString(loggerBean)));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
